package com.symbio.ishenapi.background.controller;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.symbio.ishenapi.background.bean.DoctorUser;
import com.symbio.ishenapi.background.model.TmDoctorUser;
import com.symbio.ishenapi.background.model.TmPatientSmsRecord;
import com.symbio.ishenapi.background.model.TmPatientUser;
import com.symbio.ishenapi.background.sms.SendTelMsgUtils;
import com.symbio.ishenapi.background.util.MD5Util;
import com.symbio.ishenapi.common.bean.LoginUser;
import com.symbio.ishenapi.common.controller.BaseController;
import com.symbio.ishenapi.common.kit.SecurityKit;
import io.jboot.Jboot;
import io.jboot.component.redis.JbootRedis;
import io.jboot.web.controller.annotation.RequestMapping;
import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/sms")
public class TmLoginSmsRecordController extends BaseController {

    public void sendMessage() {
        System.out.print("进入短信发送方法");

        TmPatientSmsRecord tm = (TmPatientSmsRecord) getReqBodyObject(TmPatientSmsRecord.class);
        System.out.print("获取到的手机号码为"+tm.getMobilePhone());
        if (tm.getMobilePhone() != null && !"".equals(tm.getMobilePhone())) {
            HashMap<String, Object> result = null;
            //System.out.println("验证码是：" + randNum);
            //String result = sendMsgTo("17611181702");
            //System.out.println(result);
            CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
            String verificationCode= SendTelMsgUtils.createRandNum();
            restAPI.init("sandboxapp.cloopen.com", "8883");// 初始化服务器地址和端口，沙盒环境配置成sandboxapp.cloopen.com，生产环境配置成app.cloopen.com，端口都是8883.
            restAPI.setAccount("8a48b5514a61a814014a70918f4f0896", "03e3102670d242a393bcba0f8dc0323b");// 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在“控制台-应用”中看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN。
            restAPI.setAppId("aaf98f894b353559014b49d7522d0a78");// 初始化应用ID，如果是在沙盒环境开发，请配置“控制台-应用-测试DEMO”中的APPID。如切换到生产环境，请使用自己创建应用的APPID
            result = restAPI.sendTemplateSMS(tm.getMobilePhone(), "180205", new String[]{verificationCode, "2"});
            System.out.println("SDKTestGetSubAccounts result=" + result);
            //插入新增发送记录
            //BaseTmPatientSmsRecord tm = (BaseTmPatientSmsRecord) getReqBodyObject(BaseTmPatientSmsRecord.class);
            String resultstate = (String) result.get("statusCode");
            if ("000000".equals(resultstate)) {
                tm.setSendState(resultstate); //拼接获取
                tm.setVerificationCode(verificationCode);
                tm.setSourceType("test"); //前端获取
                tm.setSmsDetails("【爱肾网】欢迎使用爱肾客户端，您的验证码是" + verificationCode + "请于2分钟内正确输入");
                tm.setCreateTime(new Date());
                if (tm.save()) {////保存成功
                    renderJsonError(40007);
                    return;
                } else {////保存失败提示信息
                    renderJsonError(40002,"验证码信息");
                    return;
                }
            } else {/////短信发送失败 返回错误信息
                System.out.print("短信发送失败 返回错误信息"+tm.getMobilePhone());
                renderJsonError(40008,(String) result.get("statusMsg"));
                return;
            }
        }else{////手机号为空返回错误信息
            System.out.print("手机号为空返回错误信息");
            renderJsonError(40003,"手机号码");
            return;
        }
    // 再写一个登录接口 比较对应手机号下的验证码是否有效 无效return "提示信息" 有效"查询当前手机号是否注册"
    // 如果已经注册  生成tocken  返回登录成功 由前调抓对应页面 对应userid 返回 如果没有插入到user表  对应手机号字段 返回user id 跳转由前端执行。
}

    //查询校验
    public void judge() {
        TmPatientSmsRecord tm = (TmPatientSmsRecord) getReqBodyObject(TmPatientSmsRecord.class);
        System.out.print("获取到的手机号码为"+tm.getMobilePhone());
        Date date =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
        String time = sdf.format(date);
        if("1".equals(tm.getUserType()) && tm.getUserType()!=null && !"".equals(tm.getUserType())){
            //医生登录
            TmDoctorUser doctor=new TmDoctorUser();
            doctor.setUserMobilePhone(tm.getMobilePhone());
            doctor.setPhoneMac(tm.getPhoneMac());
            if (TmPatientSmsRecord.dao.findTmPatientSmsRecord(tm).size()>0 && TmPatientSmsRecord.dao.findTmPatientSmsRecord(tm)!=null && !TmPatientSmsRecord.dao.findTmPatientSmsRecord(tm).isEmpty()) {/////验证码校验正确
                System.out.print("验证码校验正确");
                List<Record> listdoctor=TmDoctorUser.dao.seledocotr(doctor);
                DoctorUser tpu = new DoctorUser();
                tpu.setId(listdoctor.get(0).get("id"));
                tpu.setUserName(listdoctor.get(0).get("userName"));
                tpu.setUserMobilePhone(listdoctor.get(0).get("userMobilePhone"));
                tpu.setUserHeadPortrait(listdoctor.get(0).get("userHeadPortrait"));
                tpu.setPostTypeStr(listdoctor.get(0).get("postTypeStr"));
                if(listdoctor.size()>0){
                    System.out.print("已注册 生成token 返回校验成功");
                    //tpu = listdoctor.get(0);
                    doctor.setId(tpu.getId());
                    //将手机Mac地址和最新时间(最后登录时间)存到表中
                    doctor.update();

                    // 缓存用户信息
                    LoginUser _user_ = new LoginUser();
                    _user_.setId(tpu.getId().toString());
                    _user_.setUserName(tpu.getUserName());
                    _user_.setPhone(tpu.getUserMobilePhone());
                    _user_.setPicPath(tpu.getUserHeadPortrait());
                    _user_.setDoctorIds(tpu.getPostTypeStr());

                    // 保存缓存
                    String token = SecurityKit.encrypt(System.currentTimeMillis()+""+tpu.getId(),tpu.getUserMobilePhone());
                    JbootRedis redis = Jboot.me().getRedis();
                    redis.set(token, _user_);

                    // 构造返回值
                    Map<String, Object> ret = Maps.newHashMap();
                    //是否是主任医生
                    Boolean isDirector = TmDoctorUser.dao.isDirector(tpu.getId().toString());
                    tpu.setRests(isDirector.toString());
                    ret.put("token", token);
                    ret.put("info", tpu);
                    renderJsonRet(ret);
                    return;
                }else{
                    renderJsonError(40003,"对应用户");
                    return;
                }
            }else{/////手机或验证码不匹配 返回错误
                System.out.print("手机或验证码不匹配 返回错误");
                renderJsonError(40006);
                return;
            }
        }else{
            //患者登录
            TmPatientUser tm1=new TmPatientUser();
            tm1.setUserMobilePhone(tm.getMobilePhone());
            //添加最后登录时间
            tm1.setLastLoginTime(time);
            //添加手机Mac地址
            tm1.setPhoneMac(tm.getPhoneMac());
            System.out.print("获取到的手机号码为"+tm1.getUserMobilePhone());
            //TokenProccessor tocken = new TokenProccessor();
            if (TmPatientSmsRecord.dao.findTmPatientSmsRecord(tm).size()>0 && TmPatientSmsRecord.dao.findTmPatientSmsRecord(tm)!=null && !TmPatientSmsRecord.dao.findTmPatientSmsRecord(tm).isEmpty()) {/////验证码校验正确
                System.out.print("验证码校验正确");
                /////判断是否已经注册
                List<TmPatientUser> findPatientList = TmPatientUser.dao.findTmPatientUserByPhone(tm1);
                if (findPatientList.size()>0 && findPatientList!=null && !findPatientList.isEmpty()){/////已注册 生成token 返回校验成功
                    //tocken.makeToken();
                    System.out.print("已注册 生成token 返回校验成功");
                    TmPatientUser tpu = findPatientList.get(0);
                    tm1.setId(tpu.getId());
                    //将手机Mac地址和最新时间(最后登录时间)存到表中
                    tm1.update();

                    // 缓存用户信息
                    LoginUser _user_ = new LoginUser();
                    _user_.setId(tpu.getId().toString());
                    _user_.setUserName(tpu.getUserName());
                    _user_.setPicPath(tpu.getUserHeadPortrait());
                    _user_.setPhone(tpu.getUserMobilePhone());

                    // 保存缓存
                    String token = SecurityKit.encrypt(System.currentTimeMillis()+""+tpu.getId(),tpu.getUserMobilePhone());
                    JbootRedis redis = Jboot.me().getRedis();
                    redis.set(token, _user_);

                    // 构造返回值
                    Map<String, Object> ret = Maps.newHashMap();
                    ret.put("token", token);
                    ret.put("info", tpu);
                    renderJsonRet(ret);
                    return;
                    /*renderJsonRet(tpu.getId());
                    return;*/
                }else{/////没有注册 需要 保存信息  生成token  返回成功
                    tm1.setCreateTime(time);
                    System.out.print("没有注册 需要 保存信息  生成token  返回成功");
                    if (tm1.save()){
                        renderJsonRet(tm1.getId());

                        // 缓存用户信息
                        LoginUser _user_ = new LoginUser();
                        _user_.setId(tm1.getId().toString());

                        // 保存缓存
                        String token = SecurityKit.encrypt(System.currentTimeMillis()+""+tm1.getId(),tm1.getUserMobilePhone());
                        JbootRedis redis = Jboot.me().getRedis();
                        redis.set(token, _user_);

                        // 构造返回值
                        Map<String, Object> ret = Maps.newHashMap();
                        ret.put("token", token);
                        ret.put("info", _user_);
                        renderJsonRet(ret);
                        return;
                    }else {
                        renderJsonError(40002,"用户信息");
                        return;
                    }
                }
            }else{/////手机或验证码不匹配 返回错误
                System.out.print("手机或验证码不匹配 返回错误");
                renderJsonError(40006);
                return;
            }

        }


    }

    public void testErro() {
        renderJsonRet(40001);
    }

    /**
     * wy:根据手机MAC地址查询手机号
     */
    public void findMacAndPhone(){
        TmPatientUser tpu = (TmPatientUser)getReqBodyObject(TmPatientUser.class);
        TmPatientUser newTpu = tpu.findMacAndPhone(tpu);
        if (newTpu.getUserMobilePhone() == null && "".equals(newTpu.getUserMobilePhone().trim())){
            renderJsonRet(newTpu);
        }
        renderJsonError(400003,"手机");
    }

    /**
     * 退出
     */
//    public void logout() {
//        JbootRedis redis = Jboot.me().getRedis();
//        redis.del(getAttr(BYConst.USER_INFO_KEY).toString());
//
//        renderJsonRet(null);
//    }

    /**
     *
     *
     * @Author GuoShunYou
     * @Description 后台登录校验
     * @date 下午 12:01   2018/11/14
     * @return void
     */
    public void managerLogin(){
        TmDoctorUser doctor = (TmDoctorUser) getReqBodyObject(TmDoctorUser.class);
        DateTime datetime=new DateTime();
        String pinblock=MD5Util.encode(doctor.getPassword()+"ishen"+datetime);
        System.out.println("pinblock"+pinblock);

        doctor.setPassword(pinblock);
        TmDoctorUser doctorUser=TmDoctorUser.dao.getCount(doctor);
        if(doctorUser==null || "".equals(doctorUser)){
            renderJsonError(50004,"手机号或密码不匹配，登录失败");
        }else{
            Date date =new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
            String time = sdf.format(date);
            doctorUser.setLastLoginTime(time);
            if(doctorUser.update()){
                // 缓存用户信息
                LoginUser _user_ = new LoginUser();
                _user_.setId(doctorUser.getId().toString());
                _user_.setUserName(doctorUser.getUserName());
                _user_.setPicPath(doctorUser.getUserHeadPortrait());
                _user_.setPhone(doctorUser.getUserMobilePhone());

                // 保存缓存
                String token = SecurityKit.encrypt(System.currentTimeMillis()+""+doctorUser.getId(),doctorUser.getUserMobilePhone());
                JbootRedis redis = Jboot.me().getRedis();
                redis.set(token, _user_);

                // 构造返回值
                Map<String, Object> ret = Maps.newHashMap();
                ret.put("token", token);
                ret.put("info", doctorUser);
                renderJsonRet(ret);
                return;
            }
        }
    }

    public void getUser(){
        System.out.println(getLoginUser().toString());
        renderJsonRet(getLoginUser().toString());
    }
}